package paysyslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/pay"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/pay/internal/svc"
	"navi-mumbai/app/rpc/pay/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateEpay18DepositResultLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateEpay18DepositResultLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateEpay18DepositResultLogic {
	return &UpdateEpay18DepositResultLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新充值结果
func (l *UpdateEpay18DepositResultLogic) UpdateEpay18DepositResult(in *pb.UpdateEpay18DepositResultReq) (*pb.UpdateEpay18DepositResultResp, error) {
	defer utils.RecoverPanic()

	var df *pay.Epay18DepositFlow
	var err error
	df, err = l.svcCtx.Epay18DepositFlowModel.FindOne(l.ctx, in.PayGwFlowNo)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	df.TradeStatus = in.TradeStatus
	var dAmount decimal.Decimal
	dAmount, err = decimal.NewFromString(in.Amount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	df.ActualAmount = dAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale)).IntPart()

	err = l.svcCtx.Epay18DepositFlowModel.UpdateDepositResult(l.ctx, df.FlowNo, df.TradeStatus, df.ActualAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var resp pb.UpdateEpay18DepositResultResp
	resp.Uid = df.Uid
	resp.WalletFlowNo = df.WalletFlowNo
	return &resp, nil
}
